#include <stdio.h>
#include "smogsensor.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"
#include "esp_log.h"

#define ADC1_EXAMPLE_CHAN0          ADC1_CHANNEL_2  //gpio3
//ADC Attenuation
#define ADC_EXAMPLE_ATTEN           ADC_ATTEN_DB_11

//ADC Calibration

#define ADC_EXAMPLE_CALI_SCHEME     ESP_ADC_CAL_VAL_EFUSE_TP_FIT


static int adc_raw[2][10];
static const char *TAG = "ADC SINGLE";
static esp_adc_cal_characteristics_t adc1_chars;

static const char *TAG_CH[2][10] = {{"ADC1_CH6"}, {"ADC2_CH0"}};

int ppm = 0;

static bool adc_calibration_init(void)
{
    esp_err_t ret;
    bool cali_enable = false;

    ret = esp_adc_cal_check_efuse(ADC_EXAMPLE_CALI_SCHEME);
    if (ret == ESP_ERR_NOT_SUPPORTED) {
        ESP_LOGW(TAG, "Calibration scheme not supported, skip software calibration");
    } else if (ret == ESP_ERR_INVALID_VERSION) {
        ESP_LOGW(TAG, "eFuse not burnt, skip software calibration");
    } else if (ret == ESP_OK) {
        cali_enable = true;
        esp_adc_cal_characterize(ADC_UNIT_1, ADC_EXAMPLE_ATTEN, ADC_WIDTH_BIT_DEFAULT, 0, &adc1_chars);
        
    } else {
        ESP_LOGE(TAG, "Invalid arg");
    }

    return cali_enable;
}


void smog_task(void *arg)
{
    uint32_t voltage = 0;
    bool cali_enable = adc_calibration_init();


    //ADC1 config
    ESP_ERROR_CHECK(adc1_config_width(ADC_WIDTH_BIT_DEFAULT));
    ESP_ERROR_CHECK(adc1_config_channel_atten(ADC1_EXAMPLE_CHAN0, ADC_EXAMPLE_ATTEN));
    while(1)
    {
        // adc_raw[0][0] = adc1_get_raw(ADC1_EXAMPLE_CHAN0);
        // ESP_LOGI(TAG_CH[0][0], "raw  data: %d", adc_raw[0][0]);
        // if (cali_enable) {
        //     voltage = esp_adc_cal_raw_to_voltage(adc_raw[0][0], &adc1_chars);
        //     ESP_LOGI(TAG_CH[0][0], "cali data: %d mV", voltage);
        // }
        // ppm = voltage/3300.f*1000;
        // printf("ppm : %dppm\r\n",ppm);
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void smog_init(void)
{
    xTaskCreate(smog_task,"smog_task",2048,NULL,1,NULL);
}
